#include "message.h"
#include "FTP_client.h"
#include "pack.h"
#include "unpack.h"

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        printf("%s <IP> <PORT>",argv[0]);
        return -1;
    }
    //1.创建一个流式套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd == -1)
    {
        perror("socket failed");
        return -1;
    }

    //2.设置网络地址，IPv4，并且是TCP协议的
    struct sockaddr_in client;//IPv4专用结构体
    client.sin_family = AF_INET;
    client.sin_port = htons(atoi(argv[2]));//主机端口转化为网络端口
    client.sin_addr.s_addr = inet_addr(argv[1]);//点分十进制转化为二进制
    
    //3.发送连接请求
    int ret = connect(sockfd,(struct sockaddr *)&client,sizeof(client));
    if(ret == -1)
    {
        perror("connect failed");
        close(sockfd);//关闭套接字
        return -1;
    }
    printf("请输入密码:");
    while(1)
    {
        char mima[100]={0};
        fgets(mima,100,stdin);
        if(strncmp("123456",mima,6)==0)
        {
            break;
        }
        else
        {
           printf("密码错误请重新输入密码:");
        }
        
    }
    Knag();
    printf("连接成功请通信:");
    while(1)
    {
        char send_buf[1024] = {0};//获取命令的数组
        unsigned char send_cmd[2000] = {0};//发送给服务器封装的包的数组
        //unsigned char recv_cmd[10240] = {0};//接收服务器回复的数组
        char pathname[128] = {0};//命令所需要的参数
        printf("请输入指令：");
        fgets(send_buf,1023,stdin);//从终端上输入命令
        Knag();
        enum CMD_NO cmd = get_cmd(send_buf,pathname);//获取命令号并且设置好参数
        //printf("客户端获取到的cmd:%d\n",cmd);
        int send_len = Client_pack(send_cmd,pathname,cmd);//封包并且返回要发送过去的字节数
        ret = send(sockfd,(void*)send_cmd,send_len,0);//发送命令数组
        if(ret == -1)
        {
            perror("send failed");
            return -1;
        }
        if(cmd == FTP_CMD_LS)
        {
            clie_hand_ls(sockfd);
        }
        else if(cmd == FTP_CMD_GET)
        {
            int getfd=clie_hand_get(sockfd,pathname);

        }
        else if(cmd == FTP_CMD_PUT)
        {
            clie_hand_put(sockfd,pathname,cmd,send_cmd);
        }
        else if(cmd==FTP_CMD_CD)
        {
            clie_hand_cd(sockfd);
        }
        else if(cmd == FTP_CMD_BYE)
        {
            clie_hand_bye(sockfd);
            break;
        }
        else if(cmd == FTP_CMD_UNKNOWN)
        {
            clie_hand_unknown(sockfd);
        }
        else if(cmd == FTP_CMD_PWD)
        {
            clie_hand_pwd(sockfd);
        }

    }
    close(sockfd);//关闭套接字
    return 0;
}